package id.mankel.commons.util;


import id.mankel.commons.constants.ContentDispositionType;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;

import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;

public class MkDownloads {

    // TODO CSV: an issue will be caused by a string containing comma!

    public static void setResponseHeader(HttpServletResponse response, String contentType, String filename) {
        setResponseHeader(response, contentType, filename, true);
    }

    public static void setResponseHeader(HttpServletResponse response, String contentType, String filename, boolean ajax) {
        response.setContentType(contentType);

        // set the filename
        // for ajax
        // 在前端：response.headers['content-disposition'] = "attachment; filename*=UTF-8''<the_filename>"
        // use decodeURIComponent() to decode the filename
        ContentDisposition.Builder b = ContentDisposition.builder(ContentDispositionType.ATTACHMENT).filename(filename, StandardCharsets.UTF_8);
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, b.build().toString());

        // used for ajax download to get the filename
        if (ajax) {
            response.setHeader(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, HttpHeaders.CONTENT_DISPOSITION);
        }
    }

}